import { message, Spin, Drawer } from "antd";
import React, {
    useEffect,
    useLayoutEffect,
    useCallback,
    useState,
    useMemo
} from "react";
import { connect, useDispatch } from "react-redux";
import { LgSelect, LgPaginationA, LgSwitch, LgButton, LgTable, LgDatePicker } from "lancoo-web-ui";
import axiosMethod from "../../../util/axios";
import "./index.scss";
import Empty from "../../../common/component/empty";
import Search from "../../../common/component/search";
import TableList from "../../../common/component/fileList";
import Scrollbars from "react-custom-scrollbars";
import ReactJsonView from "react-json-view";
import 'lancoo-web-ui/dist/style.css'
import styles from "./index.module.scss";
import classNames from "classnames";

const SYSTEM_NAMES = {
    appletsPush: "公众号",
    appPush: "App",
    sysPush: "系统提醒",
    todoPush: "待办事项",
    mailPush: "邮件",
    smsPush: "手机短信",
    dingPush: "钉钉",
};

const SYSTEM_NUM_NAMES = {
    1: "App",
    2: "公众号",
    3: "系统提醒",
    4: "待办事项",
    5: "邮件",
    6: "手机短信",
    7: "钉钉",
};

const pageNum = 7;

// const end = new Date();
// const start = new Date();
// start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)

function BackupsReduction(props) {
    let {
        sysAddrInfo,
        userInfo,
        getTextById
    } = props;
    const dispatch = useDispatch();
    const [loadVisible, setLoadVisible] = useState(false);
    const [logData, setLogData] = useState([]);
    const [currentUser, setCurrentUser] = useState({
        text: "全部应用",
        info: ""
    });
    const [currentKind, setCurrentKind] = useState({
        text: "全部分类",
        info: ""
    });
    const [total, setTotal] = useState(0);
    const [moduleList, setModuleList] = useState([]);
    const [keyword, setKeyword] = useState("");
    const [pageIndex, setPageIndex] = useState(1);

    const [detailVisible, setDetailVisible] = useState(false)

    const [currentLog, setCurrentLog] = useState({});
    const [logModalVisible, setLogModalVisible] = useState(false);

    const [end, setEnd] = useState()
    const [start, setStart] = useState()

    const changeUser = (data) => {
        if (pageIndex !== 1) {
            setPageIndex(1);
        }
        setCurrentUser(data);
    }
    const changeKind = (data) => {
        if (pageIndex !== 1) {
            setPageIndex(1);
        }
        setCurrentKind(data);
    }

    const getSwitchItem = (key, value) => {
        const systemName = SYSTEM_NAMES[key];

        if (systemName) {
            return (
                <div className={styles["switch-item"]}>
                    <span className={styles["switch-name"]}>{systemName}</span>
                    <span
                        className={classNames(styles["switch-status"], {
                            [styles["switch-open"]]: value === "1",
                        })}
                    >
                        {value === "1" ? "开" : value === "0" ? "关" : "无"}
                    </span>
                </div>
            );
        }
    };

    //requestType 求类型，包括：1app、2公众号、3系统、4待办、5短信、6邮件、7钉钉等
    const getPushWayItem = (result = [], type = "", pusher) => {
        if (!result || !Array.isArray(result)) return <></>;

        const resultGroupItem = result.find((i) => {
            if (i.requestType && i.requestType === type) return true;
            return false;
        });

        // console.log(resultGroupItem, "resultGroupItem");

        const { requestLogGroupDetailList } = resultGroupItem || {};
        if (
            !Array.isArray(requestLogGroupDetailList) ||
            !requestLogGroupDetailList.length
        )
            return <span>无推送</span>;

        const pushErrorCount = requestLogGroupDetailList.reduce((pre, next) => {
            if (next.requestResult && next.requestResult === "0") {
                return pre + 1;
            }
            return pre;
        }, 0);

        requestLogGroupDetailList.sort((a, b) => {
            if (a.requestResult === "0" && b.requestResult !== "0") {
                return -1; // a 排在前面
            } else if (a.requestResult !== "0" && b.requestResult === "0") {
                return 1; // b 排在前面
            }
            return 0; // 保持原来的顺序，或者可以进一步根据其他字段排序
        });

        const isError = pushErrorCount > 0;
        const pushStatusText = isError ? "异常" : "正常";
        requestLogGroupDetailList.forEach((r) => {
            r["pusher"] = pusher;
        });

        return (
            <div className={styles["push-way-wrapper"]}>
                <span
                    className={classNames(styles["push-way-status"], {
                        [styles["push-way-normal"]]: !isError,
                        [styles["push-way-error"]]: isError,
                    })}
                >
                    {pushStatusText}
                </span>
                <div
                    className={styles["push-way-icon"]}
                    onClick={() => handleShowDetail(requestLogGroupDetailList)}
                >
                    {isError && <div className={styles["error-icon"]}></div>}
                    <div className={styles["detail-icon"]}></div>
                </div>
            </div>
        );
    };

    const handleShowDetail = (resultItem) => {
        console.log(resultItem[0])
        setCurrentLog(resultItem);
        setLogModalVisible(true);
    };

    const columns = [
        {
            dataIndex: "serial",
            key: "serial",
            align: "center",
            width: 50,
            fixed: "left",
            render: (value, record, index) => {
                return <span className={styles["serial"]}>{index + 1}</span>;
            },
        },
        {
            title: "推送方",
            dataIndex: "pusher",
            key: "pusher",
            width: 120,
            fixed: "left",
            render: (value = "") => {
                return (
                    <span className={styles["push-system"]} title={value}>
                        {value}
                    </span>
                );
            },
        },
        {
            title: "事件",
            dataIndex: "eventContent",
            key: "eventContent",
            render: (value) => {
                return (
                    <span className={styles["push-event"]} title={value}>
                        {value}
                    </span>
                );
            },
        },
        {
            title: "推送时间",
            dataIndex: "createTime",
            key: "createTime",
            width: 160,
            align: "center",
            render: (value) => {
                return <span className={styles["push-time"]}>{value}</span>;
            },
        },
        {
            title: "推送开关设置",
            dataIndex: "pushSwitchSetting",
            key: "pushSwitchSetting",
            width: 303,
            render: (value = {}) => {
                const keys = Object.keys(value);
                return (
                    <div className={styles["push-switch"]}>
                        {keys.map((key) => getSwitchItem(key, value[key]))}
                    </div>
                );
            },
        },
        {
            title: "公众号推送",
            dataIndex: "requestLogDetailList",
            key: "applet",
            width: 99,
            render: (value, record) => {
                const { requestLogGroupVoList, pusher } = record || {};
                return getPushWayItem(requestLogGroupVoList, "2", pusher);
            },
        },
        {
            title: "app推送",
            dataIndex: "requestLogDetailList",
            key: "app",
            width: 99,
            render: (value, record) => {
                const { requestLogGroupVoList, pusher } = record || {};
                return getPushWayItem(requestLogGroupVoList, "1", pusher);
            },
        },
        {
            title: "系统提醒推送",
            dataIndex: "requestLogDetailList",
            key: "system",
            width: 109,
            render: (value, record) => {
                const { requestLogGroupVoList, pusher } = record || {};
                return getPushWayItem(requestLogGroupVoList, "3", pusher);
            },
        },
        {
            title: "待办事项推送",
            dataIndex: "requestLogDetailList",
            key: "todo",
            width: 109,
            render: (value, record) => {
                const { requestLogGroupVoList, pusher } = record || {};
                return getPushWayItem(requestLogGroupVoList, "4", pusher);
            },
        },
        {
            title: "邮件推送",
            dataIndex: "requestLogDetailList",
            key: "mail",
            width: 109,
            render: (value, record) => {
                const { requestLogGroupVoList, pusher } = record || {};
                return getPushWayItem(requestLogGroupVoList, "6", pusher);
            },
        },
        {
            title: "手机短信推送",
            dataIndex: "requestLogDetailList",
            key: "sms",
            width: 109,
            render: (value, record) => {
                const { requestLogGroupVoList, pusher } = record || {};
                return getPushWayItem(requestLogGroupVoList, "5", pusher);
            },
        },
        {
            title: "钉钉推送",
            dataIndex: "requestLogDetailList",
            key: "ding",
            width: 109,
            render: (value, record) => {
                const { requestLogGroupVoList, pusher } = record || {};
                return getPushWayItem(requestLogGroupVoList, "7", pusher);
            },
        },
        {
            title: "",
            dataIndex: "projectDescription",
            key: "projectDescription",
            width: 44,
            render: (value) => {
                return <span className={styles["empty-col"]}></span>;
            },
        },
    ];

    const getMessageCenterLogList = useCallback(() => {
        setLoadVisible(true);
        console.log(userInfo)

        axiosMethod({
            type: "get",
            baseUrl: `${sessionStorage.getItem("PsnMgrLgAssistantAddr")}`,
            url: "api/logManage/getList",
            noCheck: true,
            body: {
                schoolId: userInfo.eduId,
                startTime:start ? start.toISOString().slice(0, 10) + " 00:00:00" : "",
                endTime: end ? end.toISOString().slice(0, 10) + " 23:59:59" : "",
                pageSize: pageNum,
                pageNum: pageIndex,
                keyword
            },
            callback: function (res, info) {
                console.log(info);
                const data = info.data || [];
                const total = info.total || 0;
                console.log(data)
                setTotal(total);
                setLogData(data);
                setLoadVisible(false);
            }
        });
    }, [userInfo, currentUser, currentKind, pageIndex, keyword, start, end]);

    const ModuleListDom = useMemo(() => {
        let list = JSON.parse(JSON.stringify(moduleList));
        list.forEach((item, index) => {
            item.updateTitle = (
                <div className="table-update-title" key={index}>
                    <span className="module-icon" style={{
                        backgroundImage: `url('${item.moduleLogoUrl}')`
                    }}></span>
                    <p className="module-title" title={item.productName}>{item.productName}</p>
                </div>
            )
            item.operate_btn = (
                <div className="table-btn-group">
                    <span className="blue-btn" onClick={() => {
                        dispatch({
                            type: "SET_BACKUPSHISTORYINFO",
                            data: {
                                visible: true,
                                data: item
                            }
                        })
                    }}>历史记录</span>
                </div>
            )
        })
        return (
            <TableList
                tableHeader={columns}
                pageIndex={pageIndex}
                pageSize={pageNum}
                // getList={changeCount}
                scrollbar={false}
                emptyText={keyword ? "搜素结果为空" : ""}
                data={list}
            ></TableList>
        )
    }, [keyword, moduleList, getTextById, pageIndex, dispatch]);

    const FixedColumn = useCallback(() => {
        return (
            <div {...props}>
                <LgTable columns={columns} data={logData} emptyText="暂无数据" bordered scroll={{ x: "max-content" }} />
            </div>
        );
    }, [logData])

    useEffect(() => {
        getMessageCenterLogList();
    }, [getMessageCenterLogList]);

    return (
        <div className="backups-reduction-page">
            <div className="page-top-option">
                <div>
                    <div>
                        <LgDatePicker type="B" value={[start, end]}
                            placeholder="开始时间 ~ 结束时间"
                            onChange={e => {
                                if (e instanceof Array) {
                                    setStart(e[0])
                                    setEnd(e[1])
                                    console.log("start:", e[0].toISOString().slice(0, 10), "end:", e[1].toISOString().slice(0, 10))
                                }
                            }
                            } />
                        <span className="list-num">共<span>{total}</span>条记录</span>

                    </div>
                </div>
                <Search placeholder="搜索关键词..." searchMethod={(value) => {
                    if (pageIndex !== 1) {
                        setPageIndex(1);
                    }
                    setKeyword(value)
                }} />
            </div>
            {/* {FixedColumn} */}
            <LgTable columns={columns} data={logData} bordered scroll={{ x: "max-content" }} />
            {
                total > pageNum ?
                    <div className="menu_pagination">
                        <LgPaginationA
                            total={Math.ceil(total / pageNum)}
                            size="normal"
                            currentPage={pageIndex}
                            onChangePage={(value) => {
                                setPageIndex(value);
                            }}
                            errorPage={() => { }}
                        ></LgPaginationA>
                    </div> :
                    ""
            }
            <Drawer
                title="通知推送详情"
                width={900}
                className='detail-drawer'
                onClose={() => setLogModalVisible(false)}
                visible={logModalVisible}>
                <div className="info-option">
                    <span className='option-name'>责任方:</span>
                    <span className='option-value'>{currentLog[0]?.pusher}</span>
                </div>
                {
                    currentLog[0]?.cause ?
                        <div className="info-option">
                            <span className='option-name'>原因:</span>
                            <span className='option-value'>{currentLog[0]?.cause}</span>
                        </div> :
                        ""
                }

                <div className="info-option">
                    <span className='option-name'>接口:</span>
                    <span className='option-value'>{currentLog[0]?.requestUrl}</span>
                </div>
                <div className="info-option" style={{ marginTop: 12 }}>
                    <span className='option-name' style={{ marginTop: 10 }}>参数:</span>
                    <ReactJsonView
                        name={false}
                        indentWidth={4}
                        iconStyle='triangle'
                        src={currentLog[0]?.requestParam ? JSON.parse(currentLog[0]?.requestParam) : {}}
                        displayObjectSize={false}
                        displayDataTypes={false}
                        enableClipboard={false}
                        // sortKeys
                        quotesOnKeys={true} />
                </div>
            </Drawer>
        </div>
    )
}
const mapToProps = (state) => {
    return {
        sysAddrInfo: state.sysAddrInfo,
        userInfo: state.userInfo,
        getTextById: state.getTextById
    }
}
export default connect(mapToProps)(BackupsReduction);